package com.atguigu.gulimall.product.service.impl;

import com.atguigu.common.constant.ProductConstant;
import com.atguigu.gulimall.product.dao.AttrAttrgroupRelationDao;
import com.atguigu.gulimall.product.dao.AttrGroupDao;
import com.atguigu.gulimall.product.dao.CategoryDao;
import com.atguigu.gulimall.product.entity.AttrAttrgroupRelationEntity;
import com.atguigu.gulimall.product.entity.AttrGroupEntity;
import com.atguigu.gulimall.product.entity.ProductAttrValueEntity;
import com.atguigu.gulimall.product.service.CategoryService;
import com.atguigu.gulimall.product.vo.AttrRespVo;
import com.atguigu.gulimall.product.vo.AttrVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;

import com.atguigu.gulimall.product.dao.AttrDao;
import com.atguigu.gulimall.product.entity.AttrEntity;
import com.atguigu.gulimall.product.service.AttrService;
import org.springframework.transaction.annotation.Transactional;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {

    @Autowired
    private AttrAttrgroupRelationDao relationDao;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    CategoryDao categoryDao;

    @Autowired
    AttrGroupDao attrGroupDao;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        save(attrEntity);
        //保存关联关系
        if (attr.getAttrType().equals(ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) && attr.getAttrGroupId() != null) {
            AttrAttrgroupRelationEntity attrAttrgroupRelation = new AttrAttrgroupRelationEntity();
            attrAttrgroupRelation.setAttrId(attrEntity.getAttrId());
            attrAttrgroupRelation.setAttrGroupId(attr.getAttrGroupId());
            relationDao.insert(attrAttrgroupRelation);
        }
    }

    @Override
    public PageUtils queryBaseAttrPage(Long catelogId, Map<String, Object> params, String attrType) {
        LambdaQueryWrapper<AttrEntity> queryWrapper = Wrappers.<AttrEntity>lambdaQuery().eq(AttrEntity::getAttrType, "base".equals(attrType) ? 1 : 0);
        if (catelogId != null && catelogId != 0) {
            queryWrapper.eq(AttrEntity::getCatelogId, catelogId);
        }
        Object key = params.get("key");
        if (key != null && StringUtils.isNotBlank(key.toString())) {
            queryWrapper.and((obj) -> {
                obj.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
            });
        }

        IPage<AttrEntity> page = page(new Query<AttrEntity>().getPage(params), queryWrapper);

        PageUtils pageUtils = new PageUtils(page);

        List<AttrRespVo> attrRespVos = page.getRecords().stream().map((attr) -> {
            AttrRespVo attrRespVo = new AttrRespVo();
            BeanUtils.copyProperties(attr, attrRespVo);
            attrRespVo.setCatelogName(categoryDao.selectById(attr.getCatelogId()).getName());
            if ("base".equals(attrType)) {
                AttrAttrgroupRelationEntity attrAttrgroupRelation = relationDao.selectOne(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId()));
                if (attrAttrgroupRelation != null) {
                    attrRespVo.setGroupName(attrGroupDao.selectById(attrAttrgroupRelation.getAttrGroupId()).getAttrGroupName());
                }
            }
            return attrRespVo;
        }).collect(Collectors.toList());
        pageUtils.setList(attrRespVos);
        return pageUtils;
    }

    @Override
    public AttrRespVo detail(Long attrId) {
        AttrEntity attrEntity = getById(attrId);
        if (attrEntity == null) {
            return null;
        }
        AttrRespVo attrRespVo = new AttrRespVo();
        BeanUtils.copyProperties(attrEntity, attrRespVo);
        //分类完整路径
        attrRespVo.setCatelogPath(categoryService.findCatelogPath(attrEntity.getCatelogId()));
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //设置分组信息
            AttrAttrgroupRelationEntity relation = relationDao.selectOne(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrId, attrId));
            if (relation != null) {
                attrRespVo.setAttrGroupId(relation.getAttrGroupId());
            }
        }
        return attrRespVo;
    }

    @Override
    @Transactional
    public void updateAttr(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        //更新属性
        updateById(attrEntity);
        if (attrEntity.getAttrType() == ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()) {
            //找到属性与分组关系
            AttrAttrgroupRelationEntity relation = relationDao.selectOne(Wrappers.<AttrAttrgroupRelationEntity>lambdaQuery().eq(AttrAttrgroupRelationEntity::getAttrId, attr.getAttrId()));
            //新增关系
            if (relation == null) {
                relation = new AttrAttrgroupRelationEntity();
                BeanUtils.copyProperties(attr, relation);
                relationDao.insert(relation);
            } else {
                //分组id改变了，就更新关系
                if (!Objects.equals(relation.getAttrGroupId(), attr.getAttrGroupId())) {
                    relation.setAttrGroupId(attr.getAttrGroupId());
                    relationDao.updateById(relation);
                }
            }
        }

    }

    @Override
    public PageUtils getNoattrRelation(Long attrGroupId, Map<String, Object> params) {

        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrGroupId);
        Long catelogId = attrGroupEntity.getCatelogId();

        LambdaQueryWrapper<AttrEntity> queryWrapper = Wrappers.lambdaQuery();

        List<Long> ids = relationDao.selectList(null).stream().map(AttrAttrgroupRelationEntity::getAttrId).collect(Collectors.toList());
        if (!ids.isEmpty()) {
            queryWrapper.notIn(AttrEntity::getAttrId, ids);
        }
        queryWrapper.eq(AttrEntity::getAttrType, ProductConstant.AttrEnum.ATTR_TYPE_BASE.getCode()).eq(AttrEntity::getCatelogId, catelogId);
        Object key = params.get("key");
        if (key != null && StringUtils.isNotBlank(key.toString())) {
            queryWrapper.and((obj) -> {
                obj.eq(AttrEntity::getAttrId, key).or().like(AttrEntity::getAttrName, key);
            });
        }
        IPage<AttrEntity> attrEntityIPage = page(new Query<AttrEntity>().getPage(params), queryWrapper);

        return new PageUtils(attrEntityIPage);
    }

}